//
//  JSMainViewController.swift
//  weibo
//
//  Created by 李金胜 on 16/4/6.
//  Copyright © 2016年 李金胜. All rights reserved.
//

import UIKit

class JSMainViewController: UITabBarController {
    /// 点击撰写按钮
    /// 如果`单纯`使用 `private` 运行循环将无法正确发送消息，导致崩溃
    /// 如果使用 @objc 修饰符号，可以保证运行循环能够发送此消息，即使函数被标记为 private
    @objc private func clickComposedButton() {
        print("点我了")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildViewControllers()
        
        setupComposedButton()
    }
    override func viewWillAppear(animated: Bool) {
        //初始化
        super.viewWillAppear(animated)
        
        //将
        tabBar.bringSubviewToFront(composedButton)

        
    }
    //懒加载控件
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
}


extension JSMainViewController {
    //设置攥写按钮
    private func setupComposedButton() {
        // 1. 添加按钮
        tabBar.addSubview(composedButton)
        //hello
        // 2. 调整按钮
        let count = childViewControllers.count
        // 让按钮宽一点点，能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        //添加点击方法
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }
    
    /**
    *  添加所有的字控制器
    */
    private func setupChildViewControllers(){
        //设置tintcolor 解决渲染问题，
        //使用颜色比使用图片渲染更能够提高性能
        tabBar.tintColor = UIColor.orangeColor()
        
        setupChildViewController(JSHomeViewController(), title: "首页", imageName: "tabbar_home")
        setupChildViewController(JSMessageViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())

        setupChildViewController(JSDiscoverViewController(), title: "发现", imageName:"tabbar_discover")
        setupChildViewController(JSProfileViewController(), title: "我", imageName: "tabbar_profile")
        }
    //添加控制器
    private func setupChildViewController(vc: UIViewController, title: String, imageName: String){
        //标题
        vc.title = title;
        //图标
        vc.tabBarItem.image = UIImage(named: imageName)
        //导航控制器
        let nav = UINavigationController(rootViewController: vc)
        //加入到父控制器
        addChildViewController(nav)
        
        
    }
}
